package com.pansoft.newasset.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.core.xml.StubObject;
import com.efounder.activity.AbActivity;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.service.Registry;
import com.efounder.util.AbFragmentManager;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.google.gson.Gson;
import com.pansoft.kline.greendao.DaoSessionUtil;
import com.pansoft.kline.helper.BtcKanConfigAndRateHelper;
import com.pansoft.kline.model.ConfigCoinBean;
import com.pansoft.kline.model.ConfigMarketBean;
import com.pansoft.kline.model.ConfigSiteBean;
import com.pansoft.kline.model.KlineOptionalOrMVModel;
import com.pansoft.kline.model.MarketMenuBean;
import com.pansoft.kline.util.KLineUtil;
import com.pansoft.kline.util.MarketNumberUtils;
import com.pansoft.newasset.event.OptionMarketEvent;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.manager.CoinMarketIdManager;
import com.pansoft.openplanet.manager.CurrencyAndBourseManager;
import com.pansoft.openplanet.util.TCMathUtil;
import com.utilcode.util.SPUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.MediaType;
import okhttp3.RequestBody;

import static com.pansoft.openplanet.constant.MarketConstant.KEY_MARKET_CATEGORY_VERSION;
import static com.pansoft.openplanet.constant.MarketConstant.MARKET_SELF_CHOOSE_URL;

public class TotalAssetsActivity extends AbActivity {
    private final String TAG = "TotalAssetsActivity";
    private Timer timer;

    private List<KlineOptionalOrMVModel> klineOptionalOrMVModels = new ArrayList<>();
    private List<MarketMenuBean.DataBean.TickersBean> lastTickersBeans = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_container);
        try {
            //配置文件start 传过来的对象
          StubObject stubObject1=  (StubObject)(getIntent().getSerializableExtra("stubObject"));
            AbFragmentManager abFragmentManager = new AbFragmentManager(this);
            StubObject stubObject = Registry.getRegEntryList("TotalAssetRoot").get(0);
            if(stubObject1!=null){
                stubObject.setString("currentShowId", (String) stubObject1.getStubTable().get("currentShowId"));
            }else {
                stubObject.setString("currentShowId", getIntent().getStringExtra("currentShowId"));
            }
            BaseFragment fragment = abFragmentManager.getFragment(stubObject);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container, fragment)
                    .commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        timer = new Timer();

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                remoteOptionalData();
            }
        },200,10000);
    }

    public static void start(Context context, String currentShowId) {
        Intent starter = new Intent(context, TotalAssetsActivity.class);
        starter.putExtra("currentShowId", currentShowId);
        context.startActivity(starter);
    }

    /**
     * 请求ETH的行情数据
     * eth 7843
     * btc 7496
     * Eos 7505
     *
     */
    private void remoteOptionalData() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("category_version", SPUtils.getInstance().getString(KEY_MARKET_CATEGORY_VERSION, "1") + "" );
        hashMap.put("market_ids", CoinMarketIdManager.getMarketIdList());
        String json = null;
        try {
            json = new JSONObject(hashMap.toString()).toString();

            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody requestBody = RequestBody.create(JSON, json);
            JFCommonRequestManager.getInstance(this).requestPostByAsyncWithRequsetBody(TAG, MARKET_SELF_CHOOSE_URL, requestBody, new JFCommonRequestManager.ReqCallBack<String>() {
                @Override
                public void onReqSuccess(String result) {
                    try {
                        MarketMenuBean marketMenuBean = new Gson().fromJson(result, MarketMenuBean.class);
                        if (marketMenuBean.getCode() != 0) {
                            ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                            return;
                        }
                        disposeMarketData(marketMenuBean);
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);

                    }
                }



                @Override
                public void onReqFailed(String errorMsg) {
                    //ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理市场数据
     * @param marketMenuBean
     */
    private void disposeMarketData(MarketMenuBean marketMenuBean) {
        //获取自选的集合数据
        List<MarketMenuBean.DataBean.TickersBean> tickersBeans = marketMenuBean.getData().getTickers();
        if (lastTickersBeans.size() == 0) {
            lastTickersBeans.addAll(tickersBeans);
        }
        if (tickersBeans.size() != 0) {
            klineOptionalOrMVModels.clear();
            for (int i = 0; i < tickersBeans.size(); i++) {
                if (i >= lastTickersBeans.size()) {
                    continue;
                }
                MarketMenuBean.DataBean.TickersBean tickersBean = tickersBeans.get(i);
                MarketMenuBean.DataBean.TickersBean lastTickersBean = lastTickersBeans.get(i);
                KlineOptionalOrMVModel klineOptionalOrMVModel = new KlineOptionalOrMVModel();
                //根据marketId查找币的名字
                ConfigMarketBean configMarketBean = DaoSessionUtil.getInstance().getConfigMarketBeanDao().load(tickersBeans.get(i).getId());
                klineOptionalOrMVModel.setMarketId(tickersBean.getId());
                klineOptionalOrMVModel.setName(configMarketBean.getCoin());
                //查找对应的信息
//                            ConfigCoinBean configCoinBean = DaoMaster.getDaoSessionInstance().getConfigCoinBeanDao().load(listBeans.get(j).getTitle());
//                LogUtils.e("获取到的币的信息---ConfigMarketBean-》" + configMarketBean.getCoin() + "----" + configMarketBean.getSite() +
//                        "---->" + configMarketBean.getCurrency() + "-----" + configMarketBean.getType());

                //根据查到的site查找site的title
                ConfigSiteBean configSiteBean = DaoSessionUtil.getInstance().getConfigSiteBeanDao().load(configMarketBean.getSite());
//                LogUtils.e("获取到的币的信息---configSiteBean-》" + configSiteBean.getTitle() + "----" + configSiteBean.getFee() +
//                        "---->" + configSiteBean.getUrl() + "-----" + configSiteBean.getUniqueKey());
                //根据查到的coin获取coins
                ConfigCoinBean configCoinBean = DaoSessionUtil.getInstance().getConfigCoinBeanDao().load(configMarketBean.getCoin());
//                LogUtils.e("获取到的币的信息---configCoinBean-》" + configCoinBean.getTitle() + "----" + configCoinBean.getName() +
//                        "---->" + configCoinBean.getCoin_name_other() + "-----" + configCoinBean.getSymbol());
                JSONObject rateObject = BtcKanConfigAndRateHelper.getRate(null);
                String rate = null;
                try {
                    rate = rateObject.getJSONObject(configMarketBean.getSite()).getString(configMarketBean.getCurrency());
//                    String rateRmb = rateObject.getJSONObject(configMarketBean.getSite()).getString("CNY");
                    String rateRmb = rateObject.getJSONObject(configMarketBean.getSite()).getString(CurrencyAndBourseManager.getCurrencyUnitCode());
                    double value = TCMathUtil.mul((tickersBean.getLast() / Double.valueOf(rate)) + "", rateRmb);
                    klineOptionalOrMVModel.setTitle(configSiteBean.getTitle() + "," + configCoinBean.getTitle());
                    klineOptionalOrMVModel.setPrice(CurrencyAndBourseManager.getNowCurrencySymbol() + value);

                    //将double数据转换为正常数据显示  不适用科学计数法  new BigDecimal(tickersBean.getLast()+"").toPlainString()
                    klineOptionalOrMVModel.setSubPrice(KLineUtil.getCurrencySymbol(configMarketBean.getCurrency()) + new BigDecimal(tickersBean.getLast() + "").toPlainString() + "");
//                    klineOptionalOrMVModel.setNum(configMarketBean.getCurrency() + " 量 " + conversion(tickersBeans.get(i).getVol() + "", CONVERSION_UNIT_VALUE_TEN_SHOUSAND, CONVERSION_UNIT_VALUE_POINT) + "万");
                    klineOptionalOrMVModel.setNum(configMarketBean.getCurrency() + " " + getResources().getString(R.string.chart_kline_optional_amount) + " " +
                            MarketNumberUtils.amountConversion(tickersBean.getVol()));
                    //计算涨跌幅的百分比   （last-open）/open*100
                    double changeRate = (tickersBean.getLast() - tickersBean.getOpen()) / tickersBean.getOpen() * 100;
                    //如果大于0涨  小于0跌
                    if (changeRate > 0) {
                        klineOptionalOrMVModel.setIncrease(true);
                        klineOptionalOrMVModel.setChangeRate("+" + KLineUtil.conversion(changeRate + "", "1", "0.00") + "%");
                    } else {
                        klineOptionalOrMVModel.setIncrease(false);
                        klineOptionalOrMVModel.setChangeRate(KLineUtil.conversion(changeRate + "", "1", "0.00") + "%");
                    }
                    if (tickersBean.getLast() > lastTickersBean.getLast()) {
                        klineOptionalOrMVModel.setTrendType(1);
                        tickersBean.setLastTrendType(1);
                    } else if (lastTickersBean.getLast() > tickersBean.getLast()) {
                        klineOptionalOrMVModel.setTrendType(-1);
                        tickersBean.setLastTrendType(-1);
                    } else {
                        klineOptionalOrMVModel.setTrendType(lastTickersBean.getLastTrendType());
                        tickersBean.setLastTrendType(lastTickersBean.getLastTrendType());
                    }
                    klineOptionalOrMVModels.add(klineOptionalOrMVModel);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if(klineOptionalOrMVModels.size()>0){
                OptionMarketEvent optionMarketEvent = new OptionMarketEvent();
                optionMarketEvent.setCode(0);
                optionMarketEvent.setKlineOptionalOrMVModels(klineOptionalOrMVModels);
                EventBus.getDefault().post(optionMarketEvent);
            }

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        JFCommonRequestManager.getInstance(this).cannelOkHttpRequest(TAG);
        if(timer!=null){
            timer.cancel();
            timer = null;
        }
    }
}
